#!/usr/bin/python    
#encoding=utf-8 

import tornado.httpserver
import tornado.web
import json  
import struct
#import httplib  
import urllib2
import math
import app.service.door.services.comm as comm
import app.service.door.services.db_mysql as db
from app.service.door.services.error_code import ERROR_CODE

#获取门禁ip地址
class GetIp(tornado.web.RequestHandler):
    def get(self,apikey):
		re={}
		err_code="-1"
		err_msg=ERROR_CODE[-1]

		try:
		    if not comm.Verify_ApiKey(apikey):
		        self.write(comm.NoRight_Result()) 
		        return
		    sn = comm.get_sn()
		    sn_str = comm.send_str(sn,"94")
		    # print sn_str
		    fill_send = comm.send_str_fill(sn_str) # 获取需要发送的send_message
		    door_re=comm.song_socket_Start(fill_send,comm.get_ip())
		    #解析到IP地址
		    _ip = comm.resolve_in_ip(door_re)
		    re = {"ip":_ip}
		    data=comm.build_API_Result(0,ERROR_CODE[0],re)
		    self.write(comm.dumps_API_Result(data))
		except Exception as e:
		    data=comm.build_API_Result(err_code,err_msg,{})
		    self.write(comm.dumps_API_Result(data)) 


#设置门禁ip地址
class SetIp(tornado.web.RequestHandler):
    def post(self,apikey):
		re={}
		err_code="-1"
		err_msg=ERROR_CODE[-1]
		try:
		    if not comm.Verify_ApiKey(apikey):
		        self.write(comm.NoRight_Result()) 
		        return
		    body=self.request.body
		    body=comm.Format_Validate(body)
		    if body ==-1:
		        self.write(comm.InvalidFormat_Result())
		        return  
		    doc = json.loads(body)
		    ip=doc["ip"]
		    # 将sn转义
		    sn = comm.get_sn()
		    sn_str = comm.send_str(sn,"96")
		    # fill_send = comm.send_str_fill(sn_str) 
		    # 将ip转义
		    ip_str = comm.ip_send_str(ip)
		    #控制器掩码，默认 255.255.255.0
		    son_ip_str = comm.ip_send_str("255.255.255.0")
		    #控制器网关，默认 0.0.0.0
		    gateway_str = comm.ip_send_str("0.0.0.0")
		    # 固定设置
		    fixed_set = "55aaaa55"
		    all_str = ''.join([sn_str,ip_str,son_ip_str,gateway_str,fixed_set])
		    fill_send = comm.send_str_fill(all_str)
		    print fill_send
		    # exit()
		    door_re=comm.song_socket_Start(fill_send,comm.get_ip())
		    # #解析到IP地址
		    print door_re
		    # _ip = comm.resolve_in_ip(door_re)
		    # re = {"ip":_ip}
		    # data=comm.build_API_Result(0,ERROR_CODE[0],re)
		    # self.write(comm.dumps_API_Result(data))
		except Exception as e:
		    data=comm.build_API_Result(err_code,err_msg,{})
		    self.write(comm.dumps_API_Result(data)) 

#读取服务器的卡号记录
class SelectCard(tornado.web.RequestHandler):
    def get(self,apikey):
		re={}
		err_code="-1"
		err_msg=ERROR_CODE[-1]
		try:
		    if not comm.Verify_ApiKey(apikey):
		        self.write(comm.NoRight_Result()) 
		        return
		    # 将sn转义
		    sn = comm.get_sn()
		    sn_str = comm.send_str(sn,"b0")
		    # 读取卡号的记录，默认是最后一条
		    card_num= 'ffffffff'
		    all_str = ''.join([sn_str,card_num])
		    fill_send = comm.send_str_fill(all_str)
		    # exit()
		    door_re=comm.song_socket_Start(fill_send,comm.get_ip())
		    print door_re
		    # #解析到卡号
		    _ip = comm.resolve_in_card(door_re)
		    re = {"ip":_ip}
		    data=comm.build_API_Result(0,ERROR_CODE[0],re)
		    self.write(comm.dumps_API_Result(data))
		except Exception as e:
		    data=comm.build_API_Result(err_code,err_msg,{})
		    self.write(comm.dumps_API_Result(data)) 

#card用户对象
class CardUser(tornado.web.RequestHandler):
#查询单挑记录
    def get(self,_id):
		re={}
		err_code="-1"
		err_msg=ERROR_CODE[-1]
		try:
		    apikey =self.get_argument("apikey")
		    if not comm.Verify_ApiKey(apikey):
		        self.write(comm.NoRight_Result()) 
		        return
		    mysql=db.DB_MySQL()
		    #查看该card 是否已近绑定用户，绑定就不添加
		    result=mysql.Get_CardByNoId(_id)
		    if result:
		        re["card_no"]=result[0]
		        re["user_name"]=result[1]
		        re["user_pwd"]=result[2]
		        re["group_no"]=result[3]
		    data=comm.build_API_Result(0,ERROR_CODE[0],re)
		    self.write(comm.dumps_API_Result(data))
		    return
		except Exception as e:
		    data=comm.build_API_Result(err_code,err_msg,{})
		    self.write(comm.dumps_API_Result(data)) 

#添加card用户
    def post(self):
		re={}
		err_code="-1"
		err_msg=ERROR_CODE[-1]
		try:
		    body=self.request.body
		    body=comm.Format_Validate(body)
		    if body ==-1:
		        self.write(comm.InvalidFormat_Result())
		        return  
		    doc = json.loads(body)
		    apikey = doc["apikey"]
		    if not comm.Verify_ApiKey(apikey):
		        self.write(comm.NoRight_Result()) 
		        return
		    # 将sn转义
		    sn = comm.get_sn()
		    sn_str = comm.send_str(sn,"50")
		    # 卡号
		    card_num= doc["cardNo"]
		    cart_sum = comm.card_str(card_num)
		    #起始日期，结束日期
		    start_date = "2010-01-01"
		    end_date = "2029-12-31"
		    # 将日期格式转换成BCD码
		    # bcd 转换方法   20存为 20 + (20/10)*6= 32=0x20   13存为 13 + (13/10)*6=19=0x13
		    start_time_str = comm.BCD_Str(start_date)
		    end_time_str = comm.BCD_Str(end_date)
		    #设置可以开的门
		    is_door = "01010101"  #可以打开一二号门
		    #设置用户密码
		    is_pwd = "000000"   #默认不设置密码
		    all_str = ''.join([sn_str,cart_sum,start_time_str,end_time_str,is_door,is_pwd])
		    fill_send = comm.send_str_fill(all_str)
		    add_door_re=comm.song_socket_Start(fill_send,comm.get_ip())
		    #解析是否添加成功
		    if comm.resolve_is_success(add_door_re) == False:
		         data=comm.build_API_Result("1002",ERROR_CODE[1002],{})
		         self.write(comm.dumps_API_Result(data))
		    #成功后将数据添加到数据库中
		    mysql=db.DB_MySQL()
		    result = mysql.Get_CardByNo(doc["cardNo"])
		    if result:
		         data=comm.build_API_Result(1006,ERROR_CODE[1006],{})
		         self.write(comm.dumps_API_Result(data))
		         return
		    my_sql_re=mysql.card_ins(doc["cardNo"],doc["userName"],doc["userPwd"],doc["groupNo"])
		    data=comm.build_API_Result(0,ERROR_CODE[0],{})
		    self.write(comm.dumps_API_Result(data))
		except Exception as e:
		    data=comm.build_API_Result(err_code,err_msg,{})
		    self.write(comm.dumps_API_Result(data)) 


#修改卡号用户
    def put(self,_id):
		re={}
		err_code="-1"
		err_msg=ERROR_CODE[-1]
		try:
		    body=self.request.body
		    body=comm.Format_Validate(body)
		    if body ==-1:
		        self.write(comm.InvalidFormat_Result())
		        return  
		    doc = json.loads(body)
		    apikey = doc["apikey"]
		    if not comm.Verify_ApiKey(apikey):
		        self.write(comm.NoRight_Result()) 
		        return
		    # 将sn转义
		    sn = comm.get_sn()
		    sn_str = comm.send_str(sn,"50")
		    # 卡号
		    card_num= doc["cardNo"]
		    cart_sum = comm.card_str(card_num)
		    #起始日期，结束日期
		    start_date = "2010-01-01"
		    end_date = "2029-12-31"
		    # 将日期格式转换成BCD码
		    # bcd 转换方法   20存为 20 + (20/10)*6= 32=0x20   13存为 13 + (13/10)*6=19=0x13
		    start_time_str = comm.BCD_Str(start_date)
		    end_time_str = comm.BCD_Str(end_date)
		    #设置可以开的门
		    is_door = "01010000"  #可以打开一二号门
		    #设置用户密码
		    is_pwd = "000000"   #默认不设置密码
		    all_str = ''.join([sn_str,cart_sum,start_time_str,end_time_str,is_door,is_pwd])
		    fill_send = comm.send_str_fill(all_str)
		    add_door_re=comm.song_socket_Start(fill_send,comm.get_ip())

		    if comm.resolve_is_success(add_door_re) == False:
		         data=comm.build_API_Result("1003",ERROR_CODE[1003],{})
		         self.write(comm.dumps_API_Result(data))
		    #判断该用户是否是该的card  是的就将该用户原来的权限删除
		    mysql=db.DB_MySQL()
		    user_list = mysql.Get_CardByNoId(_id)
		    if user_list[0] != doc["cardNo"]:
		         #需要将user_list["card_no"] 在服务器删除
		         sn_str = comm.send_str(sn,"52")
		         cart_sum = comm.card_str(user_list[0])
		         del_str = ''.join([sn_str,cart_sum])
		         del_str_all= comm.send_str_fill(del_str)
		         del_door_re=comm.song_socket_Start(del_str_all,comm.get_ip())
		         if comm.resolve_is_success(add_door_re) == False:
		             data=comm.build_API_Result("1003",ERROR_CODE[1003],{})
		             self.write(comm.dumps_API_Result(data))
		    #修改数据库
		    my_sql_re=mysql.card_upd(_id,doc["cardNo"],doc["userName"],doc["userPwd"],doc["groupNo"])
		    data=comm.build_API_Result(0,ERROR_CODE[0],{})
		    self.write(comm.dumps_API_Result(data))
		except Exception as e:
		    data=comm.build_API_Result(err_code,err_msg,{})
		    self.write(comm.dumps_API_Result(data)) 

#删除卡
    def delete(self,_id):
		re={}
		err_code="-1"
		err_msg=ERROR_CODE[-1]
		try: 
		    body=self.request.body
		    body=comm.Format_Validate(body)
		    if body ==-1:
		        self.write(comm.InvalidFormat_Result())
		        return  
		    doc = json.loads(body)
		    apikey = doc["apikey"]
		    card_no = doc["cardNo"]
		    if not comm.Verify_ApiKey(apikey):
		        self.write(comm.NoRight_Result()) 
		        return
		    # apikey =self.get_argument("apikey")
		    # card_no =self.get_argument("card")
		    # if not comm.Verify_ApiKey(apikey):
		    #     self.write(comm.NoRight_Result()) 
		    #     return
		    sn = comm.get_sn()
		    sn_str = comm.send_str(sn,"52")
		    # 卡号
		    cart_sum = comm.card_str(card_no)
		    all_str = ''.join([sn_str,cart_sum])
		    fill_send = comm.send_str_fill(all_str)
		    del_door_re=comm.song_socket_Start(fill_send,comm.get_ip())
		    #解析是否删除成功
		    if comm.resolve_is_success(del_door_re) == False:
		         data=comm.build_API_Result("1003",ERROR_CODE[1003],{})
		         self.write(comm.dumps_API_Result(data))
		         return
		    #成功后删除数据库
		    mysql=db.DB_MySQL()
		    #查看该card 删除
		    result=mysql.Delete_CardByNo(card_no)
		    data=comm.build_API_Result(0,ERROR_CODE[0],{})
		    self.write(comm.dumps_API_Result(data))
		    return
		except Exception as e:
		    data=comm.build_API_Result(err_code,err_msg,{})
		    self.write(comm.dumps_API_Result(data)) 
#查询卡记录  以及分页
#page   要获取的第几页
#pagesize  每页显示多少条
#
class CardUsers(tornado.web.RequestHandler):
    def post(self):
		err_code="-1"
		err_msg=ERROR_CODE[-1]
		try:
		    body=self.request.body
		    body=comm.Format_Validate(body)
		    if body ==-1:
		        self.write(comm.InvalidFormat_Result())
		        return  
		    doc = json.loads(body)
		    apikey = doc["apikey"]
		    if not comm.Verify_ApiKey(apikey):
		        self.write(comm.NoRight_Result()) 
		        return
		    page = doc["page"]
		    page_size = doc["page_size"]
		    #获取总条数
		    #成功后修改数据库
		    mysql=db.DB_MySQL()
		    count_sum= mysql.Get_CardCount()
		    if int(page_size)<0:
		        page_size =10
		    #总页数
		    page_count = int(math.ceil(int(count_sum)/float(page_size)))
		    if int(page) > int(page_count):
		         page = page_count
		    if int(page) <1:
		        page =1
		    #获取数据
		    lists = mysql.Get_CardLists(page,page_size)
		    # print lists
		    rows = []
		    for row in lists:
		    	event = {}
		        event["id"] = row[0]
		        event["card_no"] = row[1]
		        event["user_name"] = row[2]
		        event["user_pwd"] = row[3]
		        event["group_no"] = row[4]
		        rows.append(event)
		    re = {}
		    re["total"]=count_sum
		    re["page"]=int(page)
		    re["page_size"]=int(page_size)
		    re["rows"]=rows
		    # return_json["error_code"] = 0
		    # return_json["msg"] = ERROR_CODE[0]
		    # return_json["data"] = {"total": total,"page":page,"rows": rows}
		    # data=comm.build_API_Result(0,ERROR_CODE[0],re)
		    # self.write(return_json)
		    data=comm.build_API_Result(0,ERROR_CODE[0],re)
		    self.write(comm.dumps_API_Result(data)) 
		except Exception as e:
		    data=comm.build_API_Result(err_code,err_msg,{})
		    self.write(comm.dumps_API_Result(data))

    def options(self):
    	pass



#获取读卡器状态
class CardStatus(tornado.web.RequestHandler):
    def get(self):
		re={}
		err_code="-1"
		err_msg=ERROR_CODE[-1]
		try:
		    apikey =self.get_argument("apikey")
		    print apikey,sn
		    if not comm.Verify_ApiKey(apikey):
		        self.write(comm.NoRight_Result()) 
		        return
		    sn = comm.get_sn()
		    sn_str = comm.send_str(sn,"20")
		    fill_send = comm.send_str_fill(sn_str)
		    print fill_send
		    sta_door_re=comm.song_socket_Start(fill_send,comm.get_ip())
		    print sta_door_re
		    #解析出门的状态，以及门禁故障信息  
		    # status 1:打开  0:关闭   button 1：按下  0：松开   fault_num 故障数量
		    res = comm.resolve_in_status(sta_door_re)
		    print res
		except Exception as e:
		    data=comm.build_API_Result(err_code,err_msg,{})
		    self.write(comm.dumps_API_Result(data))

#删除所有权限
class CardDeleteAll(tornado.web.RequestHandler):
    def get(self):
		re={}
		err_code="-1"
		err_msg=ERROR_CODE[-1]
		try:
		    apikey =self.get_argument("apikey")
		    if not comm.Verify_ApiKey(apikey):
		        self.write(comm.NoRight_Result()) 
		        return
		    sn = comm.get_sn()
		    sn_str = comm.send_str(sn,"54")
		    sign = "55aaaa55"
		    all_str = ''.join([sn_str,sign])
		    fill_send = comm.send_str_fill(all_str)
		    sta_door_re=comm.song_socket_Start(fill_send,comm.get_ip())
		    if comm.resolve_is_success(sta_door_re) == False:
		         data=comm.build_API_Result("1004",ERROR_CODE[1004],{})
		         self.write(comm.dumps_API_Result(data))
		    data=comm.build_API_Result(0,ERROR_CODE[0],{})
		    self.write(comm.dumps_API_Result(data))
		except Exception as e:
		    data=comm.build_API_Result(err_code,err_msg,{})
		    self.write(comm.dumps_API_Result(data))


#查询卡的权限
class CardPower(tornado.web.RequestHandler):
    def get(self,card):
		re={}
		err_code="-1"
		err_msg=ERROR_CODE[-1]
		try:
		    apikey =self.get_argument("apikey")
		    if not comm.Verify_ApiKey(apikey):
		        self.write(comm.NoRight_Result()) 
		        return
		    sn = comm.get_sn()
		    sn_str = comm.send_str(sn,"5a")
		    cart_sum = comm.card_str(card)
		    all_str = ''.join([sn_str,cart_sum])
		    fill_send = comm.send_str_fill(all_str)
		    sta_door_re=comm.song_socket_Start(fill_send,comm.get_ip())
		    if comm.resolve_is_success(sta_door_re) == False:
		         data=comm.build_API_Result("1004",ERROR_CODE[1004],{})
		         self.write(comm.dumps_API_Result(data))
		    data=comm.build_API_Result(0,ERROR_CODE[0],{})
		    self.write(comm.dumps_API_Result(data))
		except Exception as e:
		    data=comm.build_API_Result(err_code,err_msg,{})
		    self.write(comm.dumps_API_Result(data))

class OpenDoor(tornado.web.RequestHandler):
    def get(self):
		re={}
		err_code="-1"
		err_msg=ERROR_CODE[-1]
		try:
		    apikey =self.get_argument("apikey")
		    door_number =self.get_argument("num")
		    if not comm.Verify_ApiKey(apikey):
		        self.write(comm.NoRight_Result()) 
		        return
		    sn = comm.get_sn()
		    sn_str = comm.send_str(sn,"40")
		    if int(door_number)==1:
		        door_str = "01"
		    elif int(door_number) ==2:
		        door_str = "02"
		    elif int(door_number) ==3:
		        door_str = "03"
		    elif int(door_number) ==4:
		        door_str = "04"
		    else: 
		          data=comm.build_API_Result("-4",ERROR_CODE[-4],{})
		          self.write(comm.dumps_API_Result(data))
		          return
		    all_str = ''.join([sn_str,door_str])
		    fill_send = comm.send_str_fill(all_str)
		    sta_door_re=comm.song_socket_Start(fill_send,comm.get_ip())
		    if comm.resolve_is_success(sta_door_re) == False:
		         data=comm.build_API_Result("1007",ERROR_CODE[1007],{})
		         self.write(comm.dumps_API_Result(data))
		    data=comm.build_API_Result(0,ERROR_CODE[0],{})
		    self.write(comm.dumps_API_Result(data))
		except Exception as e:
		    data=comm.build_API_Result(err_code,err_msg,{})
		    self.write(comm.dumps_API_Result(data))


#设置回调ip
class SetCallBackIp(tornado.web.RequestHandler):
    def get(self):
		re={}
		err_code="-1"
		err_msg=ERROR_CODE[-1]
		back_ip = "192.168.1.119"
		back_port = "8069"
		try:
		    apikey =self.get_argument("apikey")
		    if not comm.Verify_ApiKey(apikey):
		        self.write(comm.NoRight_Result()) 
		        return
		    sn = comm.get_sn()
		    sn_str = comm.send_str(sn,"90")
		    #回调ip
		    ip_str = comm.ip_send_str(back_ip)
		    #回调端口
		    port_str=comm.port_back_str(back_port)
		    all_str = ''.join([sn_str,ip_str,port_str])
		    fill_send = comm.send_str_fill(all_str)
		    sta_door_re=comm.song_socket_Start(fill_send,comm.get_ip())
		    #解析是否添加成功
		    if comm.resolve_is_success(sta_door_re) == False:
		         data=comm.build_API_Result("1003",ERROR_CODE[1003],{})
		         self.write(comm.dumps_API_Result(data))
		    data=comm.build_API_Result(0,ERROR_CODE[0],{})
		    self.write(comm.dumps_API_Result(data)) 
		except Exception as e:
		    data=comm.build_API_Result(err_code,err_msg,{})
		    self.write(comm.dumps_API_Result(data))


